package com.etrans.web.gps.business.report.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.etrans.map.tool.BaiDuConvert;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.alarm.service.AlarmService;
import com.etrans.web.gps.business.report.domain.StaticcalAnomalVo;
import com.etrans.web.gps.business.report.service.StatisticalAnomalyService;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.util.AlarmKindUtil;
import com.etrans.web.gps.util.grid.FlexiGridUtil;
import com.mongodb.QueryOperators;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/report/statisticalAnomaly/**")
public class StatisticalAnomalyController extends BaseController{
    
	@Autowired
	private StatisticalAnomalyService statisticalAnomalyService;
	
	@Autowired
	private AlarmKindUtil alarmKindUtil;
	
	@Autowired
	private AlarmService alarmService;
	
	@RequestMapping("getStatisticalAnomal.html")
	public String showStatisticalAnomal(){
		return "views/business/report/statisticalAnomal";
	}
	
	//饼图查询 
	/**
	 * 开始默认当天的数据
	 * @param req
	 * @param res
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryPieData.html")
	public List<HashMap<String, Object>> queryPieData(HttpServletRequest req,HttpServletResponse res){
		SysUser user = getSysUser();
		String vehicleId = req.getParameter("vehicleId");
		String alarmKindId = req.getParameter("alarmKindId");
		String unitId = req.getParameter("unitId");
		String startTime = req.getParameter("startTime");
		String endTime = req.getParameter("endTime");
		//计算两个日期之差
		int dateBetween = calculateDate(startTime, endTime);
		String month = startTime.substring(2);
		String dataMonth = month.replace("-", "");
		//转为int类型
		int  tableNameSuffix = Integer.parseInt(dataMonth); //得到数据库的后缀名
		
		
		Set<Integer> alarmKindIds = new HashSet<>();
	 	if (StringUtils.isNotBlank(alarmKindId)) {
		    	alarmKindIds.add(Integer.parseInt(alarmKindId));
		}else {
			alarmKindIds = alarmKindUtil.staticAnormalStr();
		}
	 	
	 	HashMap<String, Object> alarmType = new HashMap<>();
	 	alarmType.put(QueryOperators.IN, alarmKindIds);
		HashMap<String, Object> whereMap = new HashMap<>(); //构造查询条件
		if (StringUtils.isNotBlank(vehicleId)) {
			whereMap.put("vehicle_id", Integer.valueOf(vehicleId));
		}
		if (StringUtils.isNotBlank(unitId)) {
			whereMap.put("platform_id", Integer.valueOf(unitId));
		}
		whereMap.put("alarm_type", alarmType);
		
		return statisticalAnomalyService.queryDieDataMap(whereMap, tableNameSuffix,dateBetween);
	}
	
	
	@RequestMapping("querycharData.html")
	@ResponseBody
	public Map<String, Object> query(HttpServletRequest req,HttpServletResponse res){
		SysUser user = getSysUser();
		String vehicleId = req.getParameter("vehicleId");
		String alarmKindId = req.getParameter("alarmKindId");
		String unitId = req.getParameter("unitId");
		String startTime = req.getParameter("startTime");
		String endTime = req.getParameter("endTime");
		//计算两个日期之差
		int dateBetween = calculateDate(startTime, endTime);
		String month = startTime.substring(2);
		String dataMonth = month.replace("-", "");
		//转为int类型
		int  tableNameSuffix = Integer.parseInt(dataMonth); //得到数据库的后缀名
		
		
		Set<Integer> alarmKindIds = new HashSet<>();
	 	if (StringUtils.isNotBlank(alarmKindId)) {
		    	alarmKindIds.add(Integer.parseInt(alarmKindId));
		}else {
			alarmKindIds = alarmKindUtil.staticAnormalStr();
		}
	 	
	 	HashMap<String, Object> alarmType = new HashMap<>();
	 	alarmType.put(QueryOperators.IN, alarmKindIds);
		HashMap<String, Object> whereMap = new HashMap<>(); //构造查询条件
		if (StringUtils.isNotBlank(vehicleId)) {
			whereMap.put("vehicle_id", Integer.valueOf(vehicleId));
		}
		if (StringUtils.isNotBlank(unitId)) {
			whereMap.put("platform_id", Integer.valueOf(unitId));
		}
		whereMap.put("alarm_type", alarmType);
		
		//根据车辆id，时间统计数据
		return statisticalAnomalyService.getChartData(whereMap, tableNameSuffix,dateBetween);
	}
	
	//导出分析
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/exportStatisticalAnomaly.html")
	@ResponseBody
	public void exportVehicleRunning(HttpServletResponse response,HttpServletRequest request, String colModel,String vehicleId,
			String alarmKindId,String unitId, String startTime, String endTime, String title,String imgsrc,Integer page,Integer pageSize ){
		List<String> colModelList = JSON.parseObject(colModel, List.class);
		List<String> imgsrcList   = JSON.parseObject(imgsrc, List.class);
		
		
		//计算两个日期之差
		int dateBetween = calculateDate(startTime, endTime);
		String month = startTime.substring(2);
		String dataMonth = month.replace("-", "");
		//转为int类型
		int  tableNameSuffix = Integer.parseInt(dataMonth); //得到数据库的后缀名
		
		Set<Integer> alarmKindIds = new HashSet<>();
	 	if (StringUtils.isNotBlank(alarmKindId)) {
		    	alarmKindIds.add(Integer.parseInt(alarmKindId));
		}else {
			alarmKindIds = alarmKindUtil.staticAnormalStr();
		}
	 	
	 	HashMap<String, Object> alarmType = new HashMap<>();
	 	alarmType.put(QueryOperators.IN, alarmKindIds);
		HashMap<String, Object> whereMap = new HashMap<>(); //构造查询条件
		if (StringUtils.isNotBlank(vehicleId)) {
			whereMap.put("vehicle_id", Integer.valueOf(vehicleId));
		}
		if (StringUtils.isNotBlank(unitId) && !unitId.equals("null")) {
			whereMap.put("platform_id", Integer.valueOf(unitId));
		}
		whereMap.put("alarm_type", alarmType);
		//查询数据
		List<StaticcalAnomalVo> staticcalAnomalVos 
		    = statisticalAnomalyService.queryAnomalyList(whereMap,tableNameSuffix,dateBetween);
		//手动分页
		staticcalAnomalVos = staticcalAnomalVos.subList(page-1,staticcalAnomalVos.size());
		if (staticcalAnomalVos.size() > page * pageSize) {
			staticcalAnomalVos.subList(0, page * pageSize);
		}
		
		//处理数据
		List<String> pointList = new ArrayList<String>();
		
		for (int i = 0; i < staticcalAnomalVos.size(); i++) {
			StaticcalAnomalVo staticcalAnomalVo = staticcalAnomalVos.get(i);
			staticcalAnomalVo.setAlarmSource("终端报警");
			//日期转换
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		    String date =  simpleDateFormat.format((staticcalAnomalVo.getAlarm_time()));
			staticcalAnomalVo.setAlarmTime(date);
			
		    Map<Integer, String> alarmMap =  alarmService.getAlarmTypeMap();
		    String jsonStr = JSONObject.toJSONString(staticcalAnomalVo.getCoordinates());
			
		    JSONObject json = JSON.parseObject(jsonStr);
		    JSONArray points =   (JSONArray) json.get("coordinates");
			Double[] longlat = BaiDuConvert.GpsToBaidu(Double.valueOf(points.getDouble(0)),Double.valueOf(points.getDoubleValue(1)));
			pointList.add(longlat[0]+"_"+longlat[1]);
			if ((page-1)*pageSize <= i && i < page*pageSize) {
				String typeStr = alarmMap.get(staticcalAnomalVo.getAlarm_type());
				staticcalAnomalVo.setAlarmType(typeStr);
				staticcalAnomalVo.setRowNo(i + 1);
			}
		}
	
		List<HashMap<String, String>> rows = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < staticcalAnomalVos.size(); i++) {
			StaticcalAnomalVo staticcalAnomalVo = staticcalAnomalVos.get(i);
			if ((page-1)*pageSize <= i && i < page*pageSize) {
				HashMap<String, String> map = new HashMap<String, String>();	
				map.put("rowNo", i + 1 + "");
				map.put("vehicleNo",staticcalAnomalVo.getVehicle_no() ==null ? "" : staticcalAnomalVo.getVehicle_no());
				map.put("alarmType", staticcalAnomalVo.getAlarmType()==null ? "" : staticcalAnomalVo.getAlarmType());
				map.put("alarmSource", staticcalAnomalVo.getAlarmSource()==null ? "" : staticcalAnomalVo.getAlarmSource());
				map.put("alarmTime", staticcalAnomalVo.getAlarmTime()==null ? "" : staticcalAnomalVo.getAlarmTime());
				rows.add(map);
			}
		}
		List rowsList = new ArrayList<>();
		rowsList.add(rows);
		exportExl(request, response,title, removeHeadName(colModelList,-1,-1),rowsList,imgsrcList);	
	}
	
	/**
	 * 查询表格数据
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value = "queryStatisticalAnomalyListTable.html")
	public Map<String,Object>  queryStatisticalAnomalyListTable(String paramsGrid) throws ParseException{
		SysUser user = getSysUser();
		//获取查询条件
		Map<String, Object> params = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		Integer pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
		Integer page = Integer.parseInt(String.valueOf(params.get("page")));
		
		String vehicleId =  String.valueOf(params.get("vehicleId"));
		String startTime =  String.valueOf(params.get("startTime"));
		String endTime =    String.valueOf(params.get("endTime"));
		String alarmKindId =  String.valueOf(params.get("alarmKindId"));
		String unitId =   String.valueOf(params.get("unitId"));
		
		//计算两个日期之差
		int dateBetween = calculateDate(startTime, endTime);
		String month = startTime.substring(2);
		String dataMonth = month.replace("-", "");
		//转为int类型
		int  tableNameSuffix = Integer.parseInt(dataMonth); //得到数据库的后缀名
		
		Set<Integer> alarmKindIds = new HashSet<>();
	 	if (StringUtils.isNotBlank(alarmKindId)) {
		    	alarmKindIds.add(Integer.parseInt(alarmKindId));
		}else {
			alarmKindIds = alarmKindUtil.staticAnormalStr();
		}
	 	
	 	HashMap<String, Object> alarmType = new HashMap<>();
	 	alarmType.put(QueryOperators.IN, alarmKindIds);
		HashMap<String, Object> whereMap = new HashMap<>(); //构造查询条件
		if (StringUtils.isNotBlank(vehicleId)) {
			whereMap.put("vehicle_id", Integer.valueOf(vehicleId));
		}
		if (StringUtils.isNotBlank(unitId) && !unitId.equals("null")) {
			whereMap.put("platform_id", Integer.valueOf(unitId));
		}
		whereMap.put("alarm_type", alarmType);
		//查询数据
		List<StaticcalAnomalVo> staticcalAnomalVos 
		    = statisticalAnomalyService.queryAnomalyList(whereMap,tableNameSuffix,dateBetween);
		//手动分页
		staticcalAnomalVos = staticcalAnomalVos.subList(page-1,staticcalAnomalVos.size());
		if (staticcalAnomalVos.size() > page * pageSize) {
			staticcalAnomalVos.subList(0, page * pageSize);
		}
		
		//处理数据
		List<String> pointList = new ArrayList<String>();
		
		for (int i = 0; i < staticcalAnomalVos.size(); i++) {
			StaticcalAnomalVo staticcalAnomalVo = staticcalAnomalVos.get(i);
			staticcalAnomalVo.setAlarmSource("终端报警");
			//日期转换
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    String date =  simpleDateFormat.format((staticcalAnomalVo.getAlarm_time()));
			staticcalAnomalVo.setAlarmTime(date);
			
		    Map<Integer, String> alarmMap =  alarmService.getAlarmTypeMap();
		    String jsonStr = JSONObject.toJSONString(staticcalAnomalVo.getCoordinates());
			
		    JSONObject json = JSON.parseObject(jsonStr);
		    JSONArray points =   (JSONArray) json.get("coordinates");
			Double[] longlat = BaiDuConvert.GpsToBaidu(Double.valueOf(points.getDouble(0)),Double.valueOf(points.getDoubleValue(1)));
			pointList.add(longlat[0]+"_"+longlat[1]);
			
			if ((page-1)*pageSize <= i && i < page*pageSize) {
				String typeStr = alarmMap.get(staticcalAnomalVo.getAlarm_type());
				staticcalAnomalVo.setAlarmType(typeStr);
				staticcalAnomalVo.setRowNo(i + 1);
				
				//resultList.add(hashMap);
			}
		}
		//返回数据
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("rows", staticcalAnomalVos);
		resultMap.put("page", page);
		resultMap.put("total", staticcalAnomalVos.size());
		resultMap.put("pointList", pointList);
		return resultMap;
		
	}
	
    
	//计算两个日期之差
	private int calculateDate(String startDate,String endDate) {
		 SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd"); 
		 Date dateStart = null;
		 Date dateEnd = null;
		 try {
			 dateStart =  sdf.parse(startDate);
		     dateEnd = sdf.parse(endDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		  return (int) ((dateEnd.getTime() - dateStart.getTime()) / 1000 / 60 / 60 / 24);  
	}
	
	
	 
    /**
     * 根据报警类型，报警时间，报警车辆获取报警图片
     * @param alarmTime
     * @param alarmType
     * @param vehicleId
     * @return
     */
    @ResponseBody
	@RequestMapping ("/showPicture.html")
	public Map<String,Object> showPicture(String alarmTime,String vehicleNo) {
		SysUser user = getSysUser();
		return statisticalAnomalyService.queryPictureListByTime(vehicleNo,alarmTime);
	}
}
